package com.snap.vseries.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.LinearLayout;

import com.snap.vseries.R;
import com.snap.vseries.base.BaseFragment;
import com.snap.vseries.bean.ExpInfo;
import com.snap.vseries.bean.ProgramStage;
import com.snap.vseries.ui.widget.SectionView;
import com.snap.vseries.ui.widget.StageView;
import com.snap.vseries.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 程序
 */
@SuppressLint("ValidFragment")
public class ProgramFragment extends BaseFragment {
    protected List<ProgramStage> programStages;
    protected List<StageView> stageViews = new ArrayList<>();
    /**
     * //把第二层级的sectionViews 拉平成一级(循环的只记录1次）
     */
    protected List<SectionView> sectionViews = new ArrayList<>();
    @BindView(R.id.container)
    LinearLayout stageContainer;
    private ExpInfo expInfo;

    @SuppressLint("ValidFragment")
    public ProgramFragment(ExpInfo expInfo) {
        this.expInfo = expInfo;
    }

    public ProgramFragment() {
    }

    @Override
    protected int layoutResId() {
        return R.layout.fragment_program;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        initViews();
    }


    protected void initViews() {
        stageContainer.removeAllViews();
        if (expInfo == null) {
            ToastUtils.get().showText("数据为空");
            return;
        }
        programStages = expInfo.getProgram();
        if (programStages == null) {
            ToastUtils.get().showText("数据为空");
            return;
        }
        for (int i = 0; i < programStages.size(); i++) {
            if (programStages.get(i) != null && programStages.get(i).getSections() != null) {
                stageContainer.addView(new StageView(getContext(), programStages.get(i), getFragmentManager()));
            }
        }
        reCalc();
    }

    /**
     * 把所有节重新串一遍 刷新连接高度
     */
    protected void reCalc() {
        stageViews.clear();
        sectionViews.clear();
        for (int i = 0; i < stageContainer.getChildCount(); i++) {
            View v = stageContainer.getChildAt(i);
            if (v instanceof StageView) {
                stageViews.add((StageView) v);
                sectionViews.addAll(((StageView) v).getAllSectionView());
            }
        }
        if (sectionViews.size() < 1) {
            return;
        }
        //前一个节设置高度监听，后一个节响应高度变化
        for (int i = 0; i < sectionViews.size() - 1; i++) {
            //从第一个开始触发
            sectionViews.get(0).invalidate();
        }
    }

}